<?php
namespace App\Services;
use Auth;

class OrderService {
	public function createOrder($data)
	{
		$user = Auth::user();
		$goods = $user->carts()->with('goods')->get();
		$order['order_total_price'] = $order['order_real_price'] = $order['goods_total_price'] = $goods->sum->getprice();
		$order = array_merge($order, $data);
		$order = $user->orders()->create($order);
		$this->createOrderGoods($order, $goods);
		//清空购物车
		$user->carts()->delete();
		return $order;
	}

	protected function createOrderGoods($order, $goods)
	{
		foreach($goods as $v)
		{
			$row['goods_id'] = $v->goods->id;
			$row['goods_name'] = $v->goods->name;
			$row['goods_price'] = $v->goods->price;
			$row['goods_img'] = $v->goods->cover_img??'';
			$row['goods_quantity'] = $v->quantity;
			$res[] = $row;
		}
		return $order->order_goods()->createMany($res);
	}
}